package com.gitee.androidgoodies.batterylog;

import android.service.quicksettings.TileService;
import android.service.quicksettings.Tile;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.Context;

public class MainTileService extends TileService {
    private final static String TAG = "MainTileService";

    @Override
    public void onTileAdded() {
        LogUtils.d(TAG, "onTileAdded");
        super.onTileAdded();
    }

    @Override
    public void onTileRemoved() {
        LogUtils.d(TAG, "onTileRemoved");
        super.onTileRemoved();
    }

    @Override
    public void onStartListening() {
        LogUtils.d(TAG, "onStartListening");
        updateTile();
        super.onStartListening();
    }

    @Override
    public void onStopListening() {
        LogUtils.d(TAG, "onStopListening");
        super.onStopListening();
    }
    @Override
    public void onClick() {
        LogUtils.d(TAG, "onClick");
        //super.onClick();
        Tile tile = getQsTile();
        if (tile == null) {
            return;
        }
        switch (tile.getState())  {
            case Tile.STATE_ACTIVE:            {
                    tile.setState(Tile.STATE_INACTIVE);
                    tile.updateTile();
                    BatteryLogConfigUtils.setConfigIsKeepRecordService(MainTileService.this, false);
                    break;
                }
            case Tile.STATE_INACTIVE:             {
                    tile.setState(Tile.STATE_ACTIVE);
                    tile.updateTile();
                    BatteryLogConfigUtils.setConfigIsKeepRecordService(MainTileService.this, true);
                    break;
                }
            default:
                break;
        }
        // 用配置设置服务运行状态
        MainActivity.setRecordServiceStatusByConfig(MainTileService.this);
        // 通知前台窗口更新菜单
        Intent intent2 = new Intent(MainActivity.ACTION_UPDATEMENU);
        sendBroadcast(intent2);
    }
    
    public void updateTile() {
        Tile tile = getQsTile();
        if (tile != null) {
            boolean isKeepService = BatteryLogConfigUtils.getConfigIsKeepRecordService(MainTileService.this);
            if (isKeepService) { 
                tile.setState(Tile.STATE_ACTIVE);

            } else {
                tile. setState(Tile.STATE_INACTIVE);
            }
            tile.updateTile();
        }
    }
}
